<?php


namespace app\guild\controller;


use app\common\model\AdsModel;
use app\common\model\AgentModel;
use app\common\model\GuildManagerModel;
use app\common\model\GuildUserApplyModel;
use app\common\model\StatisticsModel;
use app\common\model\UserModel;
use app\common\model\UserPhotoModel;
use app\common\model\UserProfileModel;
use app\service\UserService;
use think\Db;
use think\facade\Request;
use think\Validate;

class UserController extends BaseController
{
    /**
     * 用户列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 用户列表数据
     * @return \think\response\Json
     */
    public function getlist()
    {
        $searchid       = Request::param("id");
        $searchisonline = Request::param("online_status");
        $searchaccount  = Request::param("account");
        $page           = Request::param("page");
        $limit          = Request::param("limit");

        $where[] = ['guild_id', '=', $this->guild_id];
        if ($this->hight_auth != 1) {
            $where_next   = "(FIND_IN_SET({$this->manager_id},path_ids) OR id={$this->manager_id}) AND guild_id={$this->guild_id}";
            $next_manager = GuildManagerModel::where($where_next)->column('id');
            $where[]      = ['guild_manager_id', 'in', $next_manager];
        }
        if ($searchid) {
            $where[] = ['id', '=', $searchid];
        }
        // 在线状态
        if ($searchisonline != '') {
            if ($searchisonline == 1) {
                $where[] = ['online_status', '=', $searchisonline];
            } else {
                $where[] = ['online_status', '<>', 1];
            }
        }

        if ($searchaccount != '') {
            $where[] = ['account|mobile', '=', $searchaccount];
        }

        $field    = 'id,account,mobile,nick_name,avatar,anchor_point,gold,diamond,online_status,status,sharing_ratio,regist_time,guild_manager_id';
        $userlist = UserModel::with(['profile', 'guildManager'])
            ->where($where)->field($field)
            ->limit(($page - 1) * $limit, $limit)
            ->order("regist_time", "desc")
            ->select();

        if (count($userlist) > 0) {
            $count = UserModel::where($where)->count("id");

            foreach ($userlist as &$item) {
                $item["mobile"]  = mobileHide($item['mobile']);
                $item["account"] = mobileHide($item['account']);
                $item['diamond'] = bcdiv(strval($item['diamond']), '100', 2);
                $item['gold']    = bcdiv(strval($item['gold']), '100', 2);
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 修改分成比例
     * @return \think\response\Json
     */
    public function set_sharing_ratio()
    {
        $sharing_ratio = Request::param('sharing_ratio', '0', 'intval');
        $id            = Request::param("id");


        if (!is_int($sharing_ratio) || $sharing_ratio < 0) {
            return self::bulidFail("分成比例必须为正整数");
        }

        if ($sharing_ratio < 0 || $sharing_ratio > 100) {
            return self::bulidFail("分成比例在0-100之间");
        }

        $u_where = [
            ['id', '=', $id],
            ['guild_id', '=', $this->guild_id],
        ];

        if ($this->hight_auth != 1) {
            $u_where[] = ['id', 'in', parent::getGuildUserId()];
        }

        // 主播信息
        $user_info = UserModel::where($u_where)->field('id,sharing_ratio')->find();
        if (empty($user_info)) {
            return self::bulidFail('主播信息不存在');
        }

        $user_info->sharing_ratio = $sharing_ratio;

        if ($user_info->save()) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }


    /**
     * 添加成员
     */
    function add()
    {
        // 添加成员选择归属经纪人，只能项下查询，高权限的可以选择所有
        $manager_id = $this->manager_id;
        $where      = [
            "guild_id={$this->guild_id}",
            'status=1',
            'role_id<>2'
        ];

        if ($this->hight_auth != 1) {
            $where[] = "(id={$manager_id} OR FIND_IN_SET({$manager_id},path_ids))";
        }

        $where        = implode(' AND ', $where);
        $manager_list = GuildManagerModel::with('role')->where($where)->select();

        $this->assign('manager_list', $manager_list);
        return $this->fetch();
    }

    /**
     * 添加成员-业务操作
     * @return \think\response\Json
     */
    public function add_post()
    {
        $all_request = Request::param();

        $validate = new Validate([
            'password'         => 'require|length:6,12|pass:' . config('other.alpha_num'),
            'mobile'           => 'require|pass:' . config('other.mobile_preg'),
            'nick_name'        => 'length:2,8|chsDash',
            'gender'           => 'in:1,2',
            'guild_manager_id' => 'require|egt:1'
        ], [
            "password.require"          => "请输入密码",
            "password.length"           => "密码必须在6-12位之间",
            "password.pass"             => "密码必须为字母和数字",
            "mobile.require"            => "请输入手机号",
            "mobile.pass"               => "请输入正确的手机号",
            "nick_name.length"          => "昵称长度在2-8个字符",
            "nick_name.chsDash"         => "昵称只能是汉字、字母或数字或中划线或下划线",
            "gender.in"                 => "性别选择错误",
            "guild_manager_id.required" => "请选择归属经纪人",
            "guild_manager_id.egt"      => "归属经纪人选择错误",
        ]);

        if (!$validate->check($all_request)) {
            return self::bulidFail($validate->getError());
        }

        // 查询是否有权限添加
        $manager_info = GuildManagerModel::where(['id' => $all_request['guild_manager_id'], 'guild_id' => $this->guild_id])->find();
        if (empty($manager_info)) {
            return self::bulidFail('经纪人信息不存在');
        }

        if ($manager_info->status != 1) {
            return self::bulidFail('该经纪人已被封禁');
        }

        $manager_info_path = explode(',', $manager_info->path_ids);
        $manager_info_path = array_unique(array_filter($manager_info_path));
        $manager_id        = $this->manager_id;

        // 如果是管理员权限
        if ($this->role_id > 2 && !in_array($manager_id, $manager_info_path) && $this->manager_id != $all_request['guild_manager_id']) {
            return self::bulidFail('您无权限给该经纪人添加主播');
        }

        $userModel = new UserModel($all_request);
        //检测手机号是否占用
        $mobile_where = ["mobile" => $userModel->mobile];
        $checkUser    = UserModel::where($mobile_where)->find();
        if ($checkUser) {
            return self::bulidFail("手机号已被占用");
        }

        $userModel->account         = $userModel->mobile;
        $userModel->password        = openssl_encrypt(substr($userModel->account, strlen($userModel->account) - 4, 4) . $all_request["password"], "DES-ECB", $this->OPENSSL_KEY);
        $userModel->regist_time     = nowFormat();
        $userModel->last_login      = nowFormat();
        $userModel->regist_type     = 0;
        $userModel->regist_ip       = get_client_ip();
        $userModel->guild_id        = $this->guild_id;
        $userModel->guild_join_time = nowFormat();
        // 主播账号
        $userModel->auth_time     = nowFormat();
        $userModel->sharing_ratio = 40;
        // 更改账号类型字段
        $userModel->is_anchor   = 1;
        $userModel->anchor_type = 1;

        // 写入默认头像地址
        if (!isset($userModel["avatar"]) || !$userModel["avatar"]) {
            $thumbs            = AdsModel::where(["status" => 1, "type" => 9, 'role_type' => 1])->select()->toArray();
            $thumb             = $thumbs[array_rand($thumbs, 1)];
            $userModel->avatar = $thumb["image_url"];
        }

        Db::startTrans();
        try {
            if (!$userModel->save()) {
                throw new \Exception('创建失败');
            }

            // 未填写昵称，自动创建一个昵称
            if (empty($userModel->nick_name)) {
                $userModel->nick_name = "龙门" . $userModel->id;
                if (!$userModel->save()) {
                    throw new \Exception('创建失败');
                }
            }

            //保存封面图
            $photoModel              = new UserPhotoModel();
            $photoModel->uid         = $userModel->id;
            $photoModel->img_url     = Request::param("cover_image");
            $photoModel->is_cover    = 1;
            $photoModel->create_time = date("Y-m-d H:i:s");
            if (!$photoModel->save()) {
                throw new \Exception('创建封面图失败');
            }

            // 添加代理信息
            $invite_code = createInviteCode();
            $agent_data  = [
                'uid'               => $userModel->id,
                'profit'            => 0,
                'total_profit'      => 0,
                'diamond'           => 0,
                'withdrawn_diamond' => 0,
                'invite_code'       => $invite_code,
                'created_time'      => time()
            ];
            $agent       = new AgentModel($agent_data);
            if (!$agent->save()) {
                throw new \Exception('创建失败');
            }

            // 用户性别等信息
            $userProfileModel         = new UserProfileModel($all_request);
            $userProfileModel->uid    = $userModel->id;
            $userProfileModel->gender = !empty($all_request['gender']) ? $all_request['gender'] : 0;
            if (!$userProfileModel->save()) {
                throw new \Exception('创建失败');
            }

            // 增加累计注册数据
            if (empty(StatisticsModel::setRegistPcNum())) {
                throw new \Exception('pc注册数增加错误');
            }

            // 设置es 主播数据
            if ($userModel->is_anchor == 1) {
                $res = UserService::setAnchorEs($userModel->id);
                if ($res['code'] != 0) {
                    throw new \Exception('添加信息失败');
                }
            }

            Db::commit();
            // 清理主播缓存
            UserModel::delAnchorCache();
            return self::bulidSuccess([], "添加主播成功");
        } catch (\Exception $e) {
            Db::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()], '添加信息失败');
        }
        return self::bulidFail();
    }

    /**
     * 设置经纪人
     * @return mixed
     */
    public function edit_manager()
    {
        $id         = Request::param("id");
        $manager_id = $this->manager_id;


        $u_where = [
            ['id', '=', $id],
            ['guild_id', '=', $this->guild_id],
        ];

        // 主播选择归属经纪人，只能项下查询，高权限的可以选择所有
        $where = [
            "guild_id={$this->guild_id}",
            'status=1',
            'role_id<>2'
        ];
        if ($this->hight_auth != 1) {
            $where[]   = "(id={$manager_id} OR FIND_IN_SET({$manager_id},path_ids))";
            $u_where[] = ['id', 'in', parent::getGuildUserId()];
        }

        // 主播信息
        $user_info = UserModel::where($u_where)->find();

        // 经纪人列表
        $where        = implode(' AND ', $where);
        $manager_list = GuildManagerModel::with('role')->where($where)->select();

        $this->assign('manager_list', $manager_list);
        $this->assign("user_info", $user_info);
        return $this->fetch();
    }

    /**
     * 设置经纪人-业务操作
     * @return \think\response\Json
     */
    public function edit_manager_post()
    {
        $all_request      = Request::param();
        $id               = Request::param("id");
        $guild_manager_id = Request::param('guild_manager_id');

        $validate = new Validate([
            'id'               => 'require|egt:0',
            'guild_manager_id' => 'require|egt:1'
        ], [
            "id.required"               => "没有相关主播信息",
            "id.egt"                    => "没有相关主播信息",
            "guild_manager_id.required" => "请选择归属经纪人",
            "guild_manager_id.egt"      => "归属经纪人选择错误",
        ]);

        if (!$validate->check($all_request)) {
            return self::bulidFail($validate->getError());
        }

        // 查询是否有权限添加
        $manager_info = GuildManagerModel::where(['id' => $all_request['guild_manager_id'], 'guild_id' => $this->guild_id])->find();
        if (empty($manager_info)) {
            return self::bulidFail('经纪人信息不存在');
        }

        if ($manager_info->status != 1) {
            return self::bulidFail('该经纪人已被封禁');
        }

        $manager_info_path = explode(',', $manager_info->path_ids);
        $manager_info_path = array_unique(array_filter($manager_info_path));
        $manager_id        = $this->manager_id;

        // 如果是管理员权限
        if ($this->role_id > 2 && !in_array($manager_id, $manager_info_path) && $this->manager_id != $guild_manager_id) {
            return self::bulidFail('您无权限给该经纪人添加主播');
        }


        $u_where = [
            ['id', '=', $id],
            ['guild_id', '=', $this->guild_id],
        ];

        if ($this->hight_auth != 1) {
            $u_where[] = ['id', 'in', parent::getGuildUserId()];
        }

        // 主播信息
        $user_info = UserModel::where($u_where)->find();

        $user_info->guild_id         = $this->guild_id;
        $user_info->guild_manager_id = $guild_manager_id;

        if ($user_info->save()) {
            // 清理主播缓存
            UserModel::delAnchorCache();
            return self::bulidSuccess([], "修改成功");
        }
        return self::bulidFail();
    }


    /**
     * 解约主播
     */
    function rescind()
    {
        $id = Request::param("id");

        $u_where = [
            ['id', '=', $id],
            ['guild_id', '=', $this->guild_id],
        ];

        if ($this->hight_auth != 1) {
            $u_where[] = ['id', 'in', parent::getGuildUserId()];
        }

        // 主播信息
        $user_info = UserModel::where($u_where)->field('id,guild_id,guild_manager_id')->find();
        if (empty($user_info)) {
            return self::bulidFail('主播信息不存在');
        }

        $user_info->guild_manager_id = 0;
        $user_info->guild_id         = 0;

        Db::startTrans();
        try {
            if (!$user_info->save()) {
                throw new \Exception('解约失败');
            }

            //添加解约记录
            $guild_userapply                   = new GuildUserApplyModel();
            $guild_userapply->type             = 3;
            $guild_userapply->uid              = $user_info->id;
            $guild_userapply->guild_id         = $this->guild_id;
            $guild_userapply->guild_manager_id = $this->manager_id;
            $guild_userapply->status           = 1;
            $guild_userapply->create_time      = nowFormat();
            $guild_userapply->operate_time     = nowFormat();
            if (!$guild_userapply->save()) {
                throw new \Exception('解约失败');
            }

            Db::commit();
            // 清理主播缓存
            UserModel::delAnchorCache();
            return self::bulidSuccess([], "解约成功");
        } catch (\Exception $e) {
            Db::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()], '解约失败');
        }
        return self::bulidFail('解约失败');
    }
}
